package com.neu.ui.home;

import android.content.Context;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.ViewFlipper;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProvider;
import androidx.lifecycle.ViewModelProviders;
import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

import com.bumptech.glide.Glide;
import com.google.gson.Gson;
import com.neu.R;
import com.neu.bean.Rotation;
import com.neu.bean.WeatherBean;
import com.neu.service.IService;
import com.neu.ui.BaseFragment;
import com.neu.util.RetrofitClient;
import com.neu.util.RetrofitUtil;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class HomeFragment extends BaseFragment {

    private HomeViewModel model;
    private ViewFlipper vf;
    private TextView txtWeather;


    @Override
    protected int layoutId() {
        return R.layout.fragment_home;
    }

    @Override
    protected void initView(View view) {
        vf=view.findViewById(R.id.vf);
        txtWeather=view.findViewById(R.id.txtWeather);
    }

    @Override
    protected void initData(Context context) {
        model=new ViewModelProvider(getActivity(),new ViewModelProvider.NewInstanceFactory()).get(HomeViewModel.class);
        initRotation();
        initWeather();
    }

    private void initWeather() {
       model.getWeather().observe(getViewLifecycleOwner(), new Observer<WeatherBean>() {
           @Override
           public void onChanged(WeatherBean weatherBean) {
               WeatherBean.DataBean d=weatherBean.getData();
               txtWeather.setText("今天天气："+d.getTemperature()+"°C  最高温度："+d.getMaxTemperature()+"°C");
           }
       });
    }

    private void initRotation() {
        model.getRotation().observe(getViewLifecycleOwner(), new Observer<Rotation>() {
            @Override
            public void onChanged(Rotation rotation) {
                List<Rotation.RowsBean> list=rotation.getRows();
                for(Rotation.RowsBean r:list){
                    String url=r.getAdvImg();
                    ImageView img=new ImageView(getContext());
                    img.setScaleType(ImageView.ScaleType.CENTER_CROP);
                    Glide.with(getContext()).load(RetrofitUtil.BASE_URL+url).into(img);
                    vf.addView(img);
                }
            }
        });
    }
}